<!DOCTYPE html>
<html>
<head>
<title>day02</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
/* GitHub stylesheet for MarkdownPad (http://markdownpad.com) */
/* Author: Nicolas Hery - http://nicolashery.com */
/* Version: b13fe65ca28d2e568c6ed5d7f06581183df8f2ff */
/* Source: https://github.com/nicolahery/markdownpad-github */

/* RESET
=============================================================================*/

html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
}

/* BODY
=============================================================================*/

body {
  font-family: Helvetica, arial, freesans, clean, sans-serif;
  font-size: 14px;
  line-height: 1.6;
  color: #333;
  background-color: #fff;
  padding: 20px;
  max-width: 960px;
  margin: 0 auto;
}

body>*:first-child {
  margin-top: 0 !important;
}

body>*:last-child {
  margin-bottom: 0 !important;
}

/* BLOCKS
=============================================================================*/

p, blockquote, ul, ol, dl, table, pre {
  margin: 15px 0;
}

/* HEADERS
=============================================================================*/

h1, h2, h3, h4, h5, h6 {
  margin: 20px 0 10px;
  padding: 0;
  font-weight: bold;
  -webkit-font-smoothing: antialiased;
}

h1 tt, h1 code, h2 tt, h2 code, h3 tt, h3 code, h4 tt, h4 code, h5 tt, h5 code, h6 tt, h6 code {
  font-size: inherit;
}

h1 {
  font-size: 28px;
  color: #000;
}

h2 {
  font-size: 24px;
  border-bottom: 1px solid #ccc;
  color: #000;
}

h3 {
  font-size: 18px;
}

h4 {
  font-size: 16px;
}

h5 {
  font-size: 14px;
}

h6 {
  color: #777;
  font-size: 14px;
}

body>h2:first-child, body>h1:first-child, body>h1:first-child+h2, body>h3:first-child, body>h4:first-child, body>h5:first-child, body>h6:first-child {
  margin-top: 0;
  padding-top: 0;
}

a:first-child h1, a:first-child h2, a:first-child h3, a:first-child h4, a:first-child h5, a:first-child h6 {
  margin-top: 0;
  padding-top: 0;
}

h1+p, h2+p, h3+p, h4+p, h5+p, h6+p {
  margin-top: 10px;
}

/* LINKS
=============================================================================*/

a {
  color: #4183C4;
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}

/* LISTS
=============================================================================*/

ul, ol {
  padding-left: 30px;
}

ul li > :first-child, 
ol li > :first-child, 
ul li ul:first-of-type, 
ol li ol:first-of-type, 
ul li ol:first-of-type, 
ol li ul:first-of-type {
  margin-top: 0px;
}

ul ul, ul ol, ol ol, ol ul {
  margin-bottom: 0;
}

dl {
  padding: 0;
}

dl dt {
  font-size: 14px;
  font-weight: bold;
  font-style: italic;
  padding: 0;
  margin: 15px 0 5px;
}

dl dt:first-child {
  padding: 0;
}

dl dt>:first-child {
  margin-top: 0px;
}

dl dt>:last-child {
  margin-bottom: 0px;
}

dl dd {
  margin: 0 0 15px;
  padding: 0 15px;
}

dl dd>:first-child {
  margin-top: 0px;
}

dl dd>:last-child {
  margin-bottom: 0px;
}

/* CODE
=============================================================================*/

pre, code, tt {
  font-size: 12px;
  font-family: Consolas, "Liberation Mono", Courier, monospace;
}

code, tt {
  margin: 0 0px;
  padding: 0px 0px;
  white-space: nowrap;
  border: 1px solid #eaeaea;
  background-color: #f8f8f8;
  border-radius: 3px;
}

pre>code {
  margin: 0;
  padding: 0;
  white-space: pre;
  border: none;
  background: transparent;
}

pre {
  background-color: #f8f8f8;
  border: 1px solid #ccc;
  font-size: 13px;
  line-height: 19px;
  overflow: auto;
  padding: 6px 10px;
  border-radius: 3px;
}

pre code, pre tt {
  background-color: transparent;
  border: none;
}

kbd {
    -moz-border-bottom-colors: none;
    -moz-border-left-colors: none;
    -moz-border-right-colors: none;
    -moz-border-top-colors: none;
    background-color: #DDDDDD;
    background-image: linear-gradient(#F1F1F1, #DDDDDD);
    background-repeat: repeat-x;
    border-color: #DDDDDD #CCCCCC #CCCCCC #DDDDDD;
    border-image: none;
    border-radius: 2px 2px 2px 2px;
    border-style: solid;
    border-width: 1px;
    font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
    line-height: 10px;
    padding: 1px 4px;
}

/* QUOTES
=============================================================================*/

blockquote {
  border-left: 4px solid #DDD;
  padding: 0 15px;
  color: #777;
}

blockquote>:first-child {
  margin-top: 0px;
}

blockquote>:last-child {
  margin-bottom: 0px;
}

/* HORIZONTAL RULES
=============================================================================*/

hr {
  clear: both;
  margin: 15px 0;
  height: 0px;
  overflow: hidden;
  border: none;
  background: transparent;
  border-bottom: 4px solid #ddd;
  padding: 0;
}

/* TABLES
=============================================================================*/

table th {
  font-weight: bold;
}

table th, table td {
  border: 1px solid #ccc;
  padding: 6px 13px;
}

table tr {
  border-top: 1px solid #ccc;
  background-color: #fff;
}

table tr:nth-child(2n) {
  background-color: #f8f8f8;
}

/* IMAGES
=============================================================================*/

img {
  max-width: 100%
}
</style>
</head>
<body>
<h1>Servet/JSP</h1>
<h2>回顾</h2>
<ol>
<li>
Tomcat Java WEB 服务器, 可以独立使用
<ol>
<li>安装JDK, 必须配置环境变量!!!</li>
<li>Windows 执行 TOMCAT_HOME/bin/startup.bat  
</li>
<li>
Linux 
<ol>
<li>chmod +x *.sh</li>
<li>./startup.sh </li>
</ol>
</li>
</ol>
</li>
<li>将Tomcat整合到Eclipse中使用. 开发调试使用.</li>
<li>
开始Servlet
<ol>
<li>创建maven war(Web)项目, war 项目会自动按照JAVAEE标准创建目录结构.</li>
<li>生成部署描述文件</li>
<li>导入 Tomcat 目标运行环境(Servlet API, 包含Servlet接口)</li>
<li>创建类, 实现Servlet接口.</li>
<li>配置web.xml(部署描述文件)</li>
<li>部署到Tomcat服务器  
</li>
<li>测试</li>
</ol>
</li>
</ol>
<h2>请求与响应</h2>
<p>请求与响应的原理:</p>
<p><img src="req-res.png" /></p>
<h3>HttpServletRequest</h3>
<p>HttpServletRequest 简称 request 对象, 其父类型是 ServletRequest</p>
<ol>
<li>request 对象在Tomcat收到用户请求时候创建, 其内部封装的全部的用户浏览器请求信息. </li>
<li>ServletRequest类型定义的方法少, 转换为HttpServletRequest方法更多, 使用更加方便. </li>
<li>
request对象提供了API方法, 利用这些方法可以读取用户浏览器请求的请求信息.
<ol>
<li>req.getMethod() 读取请求行中的请求方式信息 GET/POST 等</li>
<li>req.getRequestURI() 获取请求行中的 URI</li>
<li>req.getProtocol() 获取请求行中的HTTP版本</li>
<li>req.getHeader(请求头名) 获取请求头信息</li>
<li>req.getHeaderNames() 获取全部的请求头名字</li>
<li>...</li>
</ol>
</li>
</ol>
<p>案例:</p>
<ol>
<li>
<p>创建Servlet类:</p>
<pre><code>public class RequestDemoServlet 
    implements Servlet{

    public void service(
            ServletRequest request, 
            ServletResponse response) 
        throws ServletException, IOException {
        //由于getMethod方法是HttpServletRequest对象的方法
        //所以需要将ServletRequest对象强制转型才能调用
        HttpServletRequest req=
                (HttpServletRequest)request;
        //获取请求行中的请求方式(GET/POST) 
        String method=req.getMethod();
        //获取请求行中的 URI
        String uri = req.getRequestURI();
        //获取请求行中的HTTP版本
        String http = req.getProtocol();
        System.out.println(method+&quot; &quot;+uri+&quot; &quot;+http);

        //获取请求头中的信息
        String host=req.getHeader(&quot;Host&quot;);
        String ua=req.getHeader(&quot;User-Agent&quot;);

        System.out.println(host);
        System.out.println(ua);
        //获取全部的请求头信息:
        //Enumeration 与 Iterator 功能相同 
        Enumeration&lt;String&gt; em=req.getHeaderNames();
        //em.hasMoreElements() 与 it.hasNext() 相同
        //em.nextElement();    与 it.next() 相同
        while(em.hasMoreElements()) {
            String name=em.nextElement();
            System.out.println(
                    name+&quot;:&quot;+req.getHeader(name));
        }

        response.setContentType(&quot;text/html&quot;);
        response.getWriter().println(&quot;OK&quot;); 
    }

    public void destroy() {

    }

    public ServletConfig getServletConfig() {
        return null;
    }

    public String getServletInfo() {
        return null;
    }

    public void init(ServletConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }

}
</code></pre>

</li>
<li>
<p>配置web.xml</p>
<pre><code>  &lt;servlet&gt;
    &lt;servlet-name&gt;req&lt;/servlet-name&gt;
    &lt;servlet-class&gt;day02.RequestDemoServlet&lt;/servlet-class&gt;
  &lt;/servlet&gt;  
  &lt;servlet-mapping&gt;
    &lt;servlet-name&gt;req&lt;/servlet-name&gt;
    &lt;url-pattern&gt;/request-demo&lt;/url-pattern&gt;
  &lt;/servlet-mapping&gt;
</code></pre>

</li>
</ol>
<h3>HttpServletResponse</h3>
<p>HttpServletResponse 简称Response 其父类型是 ServletResponse </p>
<ol>
<li>Response用于处理服务器到客户端的响应, 其内部有一个缓冲, 用来保存响应信息. </li>
<li>ServletResponse 是父类型, 提供的方法没有 HttpServletResponse 多, 使用没有HttpServletResponse方便. 所以 HttpServletResponse 使用更多.</li>
<li>
request提供的API用来处理向客户端发送的响应信息:
<ol>
<li>res.setStatus(200) 设置状态码, 也就是设置状态行</li>
<li>res.setContentType设置Content-Type响应头, 用来通知浏览器采用何种方式处理 响应Body.</li>
<li>res.setContentLength 设置 Content-Length 响应头</li>
<li>res.getOutputStream().write() 设置响应消息正文Body</li>
<li>res.getPrintWriter() 获得设置了编码的输出流, 调用之前必须使用setContentType设置编码.</li>
<li>res.setHeader() 设置自定义的响应头</li>
</ol>
</li>
</ol>
<p>案例:</p>
<ol>
<li>
<p>编写Servlet类</p>
<pre><code>public class ResponseDemoServlet 
    implements Servlet{

    public void service(
            ServletRequest request, 
            ServletResponse response) 
        throws ServletException, IOException {
        //为了调用子类型的方法, 先进行类型转换
        HttpServletRequest req=
                (HttpServletRequest)request;
        HttpServletResponse res=
                (HttpServletResponse)response;
        //利用response对象, 处理对用户浏览器的响应
        //设置响应状态码, 默认状态码就是200
        res.setStatus(200); //400 500 302 等

        //设置响应头, 设置UTF-8支持中文
        res.setContentType(&quot;text/html; charset=utf-8&quot;);
        String str = &quot;&lt;html&gt;&lt;body&gt;&lt;h1&gt;&quot;
                + &quot;今天天气不错!&quot;
                + &quot;&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;&quot;;
        byte[] bytes = str.getBytes(&quot;utf-8&quot;);
        //设置消息正文长度
        res.setContentLength(bytes.length); 
        //添加一个自定义的响应头
        res.setHeader(&quot;msg&quot;, &quot;Hello World!&quot;); 

        //发送消息正文
        res.getOutputStream().write(bytes); 
        //将response中的信息刷出, 反馈到浏览器
        //如果不调用这个方法, Tomcat会自动调用!
        res.flushBuffer();
    }
    public void destroy() {

    }

    public ServletConfig getServletConfig() {
        return null;
    }

    public String getServletInfo() {
        return null;
    }

    public void init(ServletConfig arg0) throws ServletException {

    }


}
</code></pre>

</li>
<li>
<p>配置 web.xml</p>
<pre><code>  &lt;servlet&gt;
    &lt;servlet-name&gt;res&lt;/servlet-name&gt;
    &lt;servlet-class&gt;day02.ResponseDemoServlet&lt;/servlet-class&gt;
  &lt;/servlet&gt;
  &lt;servlet-mapping&gt;
    &lt;servlet-name&gt;res&lt;/servlet-name&gt;
    &lt;url-pattern&gt;/response-demo&lt;/url-pattern&gt;
  &lt;/servlet-mapping&gt;
</code></pre>

</li>
<li>
<p>测试: 检查浏览器中收到的响应头信息, 是否包含自定义响应头</p>
</li>
</ol>
<p>Response提供了更加简便的API, 可以替代如上的API:</p>
<ol>
<li>采用默认的状态码200</li>
<li>先设置 Content-Type 头, 包含chaeset编码</li>
<li>在创建 PrintWriter对象, printWriter对象会自动处理文本的编码,并且会自动的设置Content-Length</li>
</ol>
<p>案例:</p>
<ol>
<li>
<p>编写Servlet类</p>
<pre><code>public class ResponseDemo2Servlet
    implements Servlet{

    public void service(ServletRequest request, 
            ServletResponse response) 
        throws ServletException, IOException {
        HttpServletRequest req = 
                (HttpServletRequest) request;
        HttpServletResponse res = 
                (HttpServletResponse) response;

        //1 响应状态码 200 时候可以不设置, 默认就是200
        //2 设置ContentType响应头, 通知浏览器正文内容和编码
        res.setContentType(
                &quot;text/html;charset=utf-8&quot;);
        //3 获取 PrintWriter 对象, 字符流, 封装字符
        //  的编码功能. 按照ContentType设置编码utf-8
        PrintWriter out = res.getWriter();
        //4 设置消息正文内容
        out.print(&quot;&lt;html&gt;&lt;body&gt;&lt;h1&gt;&quot;
                + &quot;简单版本&quot;
                + &quot;&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;&quot;);
        //PrintWriter 会自动处理文字编码,设置ContentLength
    }

    public void destroy() {
    }

    public ServletConfig getServletConfig() {
        return null;
    }

    public String getServletInfo() {
        return null;
    }

    public void init(ServletConfig arg0) throws ServletException {
    }


}
</code></pre>

</li>
<li>
<p>配置web.xml</p>
<pre><code>  &lt;servlet&gt;
    &lt;servlet-name&gt;res2&lt;/servlet-name&gt;
    &lt;servlet-class&gt;day02.ResponseDemo2Servlet&lt;/servlet-class&gt;
  &lt;/servlet&gt;
  &lt;servlet-mapping&gt;
    &lt;servlet-name&gt;res2&lt;/servlet-name&gt;
    &lt;url-pattern&gt;/response2-demo&lt;/url-pattern&gt;
  &lt;/servlet-mapping&gt;
</code></pre>

</li>
<li>
<p>测试</p>
</li>
</ol>
<h2>HttpServlet</h2>
<p>实现Servlet接口创建Servlet非常繁琐, Servlet API 为了简化编程提供了更加简洁的API: HttpServlet.</p>
<p>HttpServlet实现了Servlet接口, 继承HttpServlet 就间接实现Servlet接口. </p>
<p>HttpServlet已经完整实现Servlet接口, 只需要简单重写 doGet或者doPost就可以方便的实现Servlet. </p>
<p>HttpServlet根据用户请求类型, 调用对应的doGet或者doPost方法.</p>
<p>原理: </p>
<p><img src="http.png" /></p>
<p>案例:</p>
<ol>
<li>
<p>创建Servlet类</p>
<pre><code>public class HttpDemoServlet extends HttpServlet{

    @Override
    protected void doGet(
            HttpServletRequest req,
            HttpServletResponse resp) 
        throws ServletException, IOException {

        resp.setContentType(&quot;text/html; charset=utf-8&quot;);
        PrintWriter out=resp.getWriter();
        out.print(&quot;&lt;html&gt;&lt;body&gt;&lt;h1&gt;&quot;);
        out.print(&quot;第一个HttpServlet&quot;);
        out.print(&quot;&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;&quot;);
    }

}
</code></pre>

</li>
<li>
<p>配置web.xml</p>
<pre><code>  &lt;servlet&gt;
    &lt;servlet-name&gt;httpdemo&lt;/servlet-name&gt;
    &lt;servlet-class&gt;day02.HttpDemoServlet&lt;/servlet-class&gt;
  &lt;/servlet&gt;
  &lt;servlet-mapping&gt;
    &lt;servlet-name&gt;httpdemo&lt;/servlet-name&gt;
    &lt;url-pattern&gt;/http-demo&lt;/url-pattern&gt;
  &lt;/servlet-mapping&gt;
</code></pre>

</li>
<li>
<p>测试: 可以看出来 继承HttpServlet可以大大简化Servlet编码</p>
</li>
</ol>
<p>利用Eclipse开发工具提供的Servlet向导可以快速创建Servlet, 这个功能了解即可. </p>
<h3>Request 接收表单参数</h3>
<p>Request功能很多, 其主要作用就是处理浏览器请求. 用户通过表单提交的参数可以通过Request对象提供的API方法读取</p>
<pre><code>String name = request.getParamter(&quot;name&quot;);
</code></pre>

<p>原理:</p>
<p><img src="parameter.png" /></p>
<p>案例:</p>
<ol>
<li>
<p>编写表单 webapp/login.html</p>
<pre><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta charset=&quot;UTF-8&quot;&gt;
&lt;title&gt;登录表单&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;h1&gt;登录&lt;/h1&gt;
    &lt;p&gt;使用request对象接收表单参数&lt;/p&gt;
    &lt;!-- 向 login url发起post请求 --&gt;
    &lt;form action=&quot;login&quot; method=&quot;post&quot;&gt;
        &lt;div&gt;
            &lt;label&gt;用户&lt;/label&gt;
            &lt;input type=&quot;text&quot; name=&quot;user&quot;&gt; 
        &lt;/div&gt;
        &lt;div&gt;
            &lt;label&gt;密码&lt;/label&gt;
            &lt;input type=&quot;password&quot; name=&quot;pwd&quot;&gt; 
        &lt;/div&gt;
        &lt;input type=&quot;submit&quot; value=&quot;登录&quot;&gt;   
    &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>

</li>
<li>
<p>测试显示表单</p>
</li>
<li>
<p>编写Servlet</p>
<pre><code>public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;


    protected void doPost(
            HttpServletRequest request,
            HttpServletResponse response) 
        throws ServletException, IOException {
        //利用request的API获取表单参数
        String name = request.getParameter(&quot;user&quot;);
        String pwd = request.getParameter(&quot;pwd&quot;);
        System.out.println(name+&quot;,&quot;+pwd);

        response.setContentType(
                &quot;text/html; charset=utf-8&quot;); 
        PrintWriter out=response.getWriter();
        out.print(&quot;OK&quot;); 
    }

}
</code></pre>

</li>
<li>
<p>测试</p>
</li>
</ol>
<blockquote>
<p>注意: 这个案例中有中文编码问题, 是下一节课程的内容. </p>
</blockquote>
<h2>回顾</h2>
<h3>request response</h3>
<ol>
<li>Request 对象: 接收浏览器请求消息, 提供了读取请求消息的API</li>
<li>Response 对象: 用于缓冲响应消息, 提供API设置修改响应消息.</li>
<li>Tomcat负责解析请求, 创建Request 对象</li>
<li>Tomcat负责创建Response 对象, Tomcat负责将Response对象中信息, 发送到浏览器. </li>
</ol>
<h3>创建Servlet的方式:</h3>
<ol>
<li>实现Servlet接口: 繁琐</li>
<li>继承HttpServlet: 简单</li>
<li>开发工具提供了创建Servlet向导(知道就行!)</li>
</ol>
<h3>Request 接收表单参数</h3>

</body>
</html>
<!-- This document was created with MarkdownPad, the Markdown editor for Windows (http://markdownpad.com) -->
